<?php

namespace app\api\controller;

use app\admin\model\admin\Admin;
use app\admin\model\channel\Channel;
use app\api\model\merchant\MerchantModel;
use app\api\model\order\Order;
use app\BaseController;
use app\Request;
use think\exception\ValidateException;
use think\facade\Log;
use think\facade\Queue;
use ulit\CryptAES;
use ulit\thirdPayment\SafePay;

class PaymentV1 extends BaseController
{


    public function pay(Request $request){


        if($request->isPost()){

            $params = $request->only([
                'appid', 'secret', 'channel_code','card_no',
                'name', 'withdraw_type', 'remark', 'amount',
                'account_type', 'bank_name', 'brach_bank_code', 'body', 'sign','out_trade_id','notify_url','callback_url','out_trade_id'
            ]);


            $MemberKeyInfo= MerchantModel::getMerchantInfo($params['appid'],$params['secret']);; //获取商户密钥

           $rate= Admin::where(['id'=>$MemberKeyInfo->admin_id])->value('rate');

            if(empty($MemberKeyInfo)){

                return $this->error('商户信息错误！');
            }
            //校验规则
            $rules = [
                'appid' => ['require','number','length'=>'1,10'],
                'secret' => ['require'],
                'out_trade_id' =>['require','max'=>32,'unique'=>'order'],
                'notify_url' => ['require',],
               // 'callback_url' => ['require',],
//            'ip' => ['require','ip'],
                'amount' => ['require','float','between'=>"0.01,1000000"],
                'withdraw_type' => ['require',],
                'channel_code' => ['alphaDash','length'=>'2,64'],
                'sign' => ['require','length'=>'10,255'],
            ];

            $message=[
                'appid.require'  => ['code' => 53003, 'msg' => 'appid必填'],
                'secret.require'  => ['code' => 53003, 'msg' => 'secret必填'],
                'amount.require'  => ['code' => 53003, 'msg' => '金额必须'],
                'out_trade_id.max'  => ['code' => 53004, 'msg' => '订单号最大长度为32位'],
                'money.between'  => ['code' => 53005, 'msg' => '金额必须在0.01-1000000之间'],
                'out_trade_id.unique'  => ['code' => 53004, 'msg' => '订单号已经存在'],
                'notify_url.require'  => ['code' => 53007, 'msg' => '回调通知地址必填'],
              //  'callback_url.require'  => ['code' => 53007, 'msg' => '返回地址必填'],
                'withdraw_type.require'  => ['code' => 53009, 'msg' => '支付类型必填'],
                'sign.require'  => ['code' => 53010, 'msg' => '签名必填'],
                'sign.length'  => ['code' => 53010, 'msg' => '签名最大长度255'],
            ];
            $out_trade_id= input('post.out_trade_id');
            $sign=[
                'appid'=>$request->param('appid'),
                'out_trade_id'=>$request->param('out_trade_id'),
                'amount'=>$request->param('amount'),
                'secret'=>$request->param('secret'),
                'notify_url'=>$request->param('notify_url'),
                'sign'=>$request->param('sign'),
            ];



//            $signs=makeApiSign($sign,$MemberKeyInfo->key);

           if ($MemberKeyInfo->money<0 || (($MemberKeyInfo->money-input('amount'))<0)){
               return $this->error('余额不足');
           }
            if($MemberKeyInfo->ip_switch==1){
                $ips=$MemberKeyInfo->ip;
                $ip=$request->ip();
                if(!in_array($ip,$ips)){
                    $msg=[
                        'code'=>530011,
                        'msg'=>'请把ip添加到白名单'
                    ];
                    return $this->result($msg);
                }
            }


            if(!verifyApiSign($sign,$MemberKeyInfo->key)){
                $msg=[
                    'code'=>530007,
                    'msg'=>'签名错误！'
                ];
                return $this->result($msg);
            };
            try {
                $this->validate($params, $rules, $message);
                $order_sn=getRandOrderSn();
                $cardNo=input('card_no');
                $name =input('name');
                $withdrawType=input('withdraw_type');
                $remark=input('remark');
                $amount= input('amount');
                $accountType =input('account_type');
                $bankName=input('bank_name');
                $breachBankCode=input('brach_bank_code');
                $appConfigId='discard';
                $channel_info=Channel::where(['code'=>$request->param('channel_code')])->find();
                 if(!$channel_info){
                     return  $this->error('通道编码错误');
                 }
                $rate ? $commission = floatval($amount)*($rate/100):$commission=0;
                $commission>0 ? $actual_amount=$amount-$commission:$actual_amount=$amount; //实际到账金额

                $add=[
                    'appid'=>$request->param('appid'),
                    'secret'=>$request->param('secret'),
                    'order_sn'=>$order_sn,
                    'merchant_id'=>$MemberKeyInfo->id,
                    'channel_id'=>$channel_info->id,
                    'out_trade_id'=>$out_trade_id,
                    'amount'=>$amount,
                    'status'=>0,
                    'commission'=>$commission,
                    'actual_amount'=>$actual_amount,
                    'third_ext_json'=>$request->param(''),
                ];

                $res=Order::submitOrder($add);
                if($res){
                    $result=SafePay::getInstance()->withdraw($order_sn,$cardNo,$name,$withdrawType,$remark,$actual_amount,$appConfigId,$accountType,$bankName,$breachBankCode);

                    $arr=json_decode($result,true);

                    Log::write('执行时间'.time());

                    if($arr['code']==20000){
                        $params=[
                           'order_sn'=>$order_sn,
                        ];
                        insCheckRedis($order_sn); //加入队列
                        Queue::later(2, 'app\logic\job\CanLangPay',$params); //延迟2s

                    return    $this->success(['order_sn'=>$order_sn]);
                    }else{

                        if(empty($result)){
                            $error_json=['msg'=>'支付服务网络异常'];
                            $msg='支付服务网络异常';
                        }else{
                            $error_json=$result;
                            $msg=$arr['message'];
                        }

                        Order::where(['order_sn'=>$order_sn])->update(['pay_error_json'=>$error_json]);
                    return    $this->error($msg);

                    }
                }

                return    $this->error('添加订单失败');

            }catch (ValidateException $e){
                // 验证失败 输出错误信息

                Log::write($e->getMessage());

                return $this->result($e->getError());
            }


        }

        return $this->error('未知错误');

    }

    public function findOrder(Request $request){

        $params=$request->param('');




        $MemberKeyInfo= MerchantModel::getMerchantInfo($params['appid'],$params['secret']);; //获取商户密钥
        if(empty($MemberKeyInfo)){

            return $this->error('商户信息错误！');
        }
        $sign=[
            'appid'=>$request->param('appid'),
            'out_trade_id'=>$request->param('out_trade_id'),
            'secret'=>$request->param('secret'),
            'notify_url'=>$request->param('notify_url'),
            'sign'=>$request->param('sign'),
        ];
//            if(!verifyApiSign($sign,$MemberKeyInfo->key)){
//                $msg=[
//                    'code'=>530007,
//                    'msg'=>'签名错误！'
//                ];
//                return $this->result($msg);
//            };

        $out_trade_id=$request->param('out_trade_id');

        $order_info=Order::where(['out_trade_id'=>$out_trade_id])->field('order_sn')->find();


        if(!$order_info){
            return $this->error('订单信息不存在');
        }

        $result=SafePay::getInstance()->query($order_info->order_sn);

        $res=json_decode($result,true);


        $res['code'] ==20000 ?$code=200:$code=$res['code'];

        $data['orderCode']=$res['result']['orderCode'];
        $data['payMoney']=$res['result']['payMoney'];
        $data['payTime']=$res['result']['payTime'];
        $data['orderStatus']=$res['result']['orderStatus'];
        $data['remark']=$res['result']['remark'];
        return $this->result(['code'=>$code,'msg'=>$res['message'],'data'=>$data]);
    }

    public function notify()
    {
        $data=input('');

        Log::write(json_encode($data));
        exit('success');
    }

}